package org.renhj.provider.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import org.renhj.common.RpcResponse;
import org.renhj.provider.service.SpringContext;
import org.renhj.common.RpcRequest;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

public class RpcProviderHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接: " + ctx.channel().remoteAddress() );
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ApplicationContext applicationContext = SpringContext.getApplicationContext();

        System.out.println(msg);
        RpcRequest rpcRequest = (RpcRequest) msg;
        Object bean = applicationContext.getBean(Class.forName(rpcRequest.getClassName()));
        Method method = bean.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(bean, rpcRequest.getParameters());

        RpcResponse response = new RpcResponse();
        response.setRequestId(rpcRequest.getRequestId());
        response.setResult(result);

        ctx.writeAndFlush(response);
    }

}
